// ignore_for_file: slash_for_doc_comments

/*
 * @FilePath: \flutter_ducafecat_news_getx\lib\pages\main\controller.dart
 * @Date: 2022-07-11 14:53:48
 * @LastEditTime: 2022-07-22 11:02:06
 * @Description: 
 */
import 'dart:async';

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/material.dart';
import 'package:flutter_ducafecat_news_getx/common/apis/apis.dart';
import 'package:flutter_ducafecat_news_getx/common/entities/entities.dart';
import 'package:flutter_ducafecat_news_getx/common/routers/names.dart';
import 'package:flutter_ducafecat_news_getx/pages/main/widgets/hotbo.dart';
import 'package:get/get.dart';
import 'index.dart';

class MainController extends GetxController {
  MainController();

  /// 响应式成员变量

  final state = MainState();
  var hotHx = 0.0;
  int last = 0;
  double nextponit = 0;

  ///热点播客左右滑动控制器
  ScrollController hotControl = ScrollController();

  ///音乐播放器
  AudioPlayer player = AudioPlayer();
  AudioCache cachePlayer = AudioCache();
  //控制音频播放

  /// 成员变量

  /// 方法
  ///播放音乐,暂停，停止
  play() {
    try {
      cachePlayer.fixedPlayer = player;
      cachePlayer.play('musics/yhxk.mp3');
      log.d('success');
    } catch (e) {
      log.e(e);
    }
  }

  ///暂停播放音乐
  pause() {
    cachePlayer.fixedPlayer!.pause();
    log.d('点击暂停');
  }

  ///去到音乐播放页面
  goToMusicPlay() {
    Get.toNamed(AppRoutes.MusicPlay);
  }

  // 拉取数据
  asyncLoadAllData() async {
    state.categories = await NewsAPI.categories(
      cacheDisk: true,
    );
    state.channels = await NewsAPI.channels(
      cacheDisk: true,
    );
    state.newsRecommend = await NewsAPI.newsRecommend(
      cacheDisk: true,
    );
    state.newsPageList = await NewsAPI.newsPageList(
      cacheDisk: true,
    );

    state.selCategoryCode = state.categories.first.code;
  }

  // 拉取推荐、新闻
  asyncLoadNewsData(
    categoryCode, {
    bool refresh = false,
  }) async {
    state.selCategoryCode = categoryCode;
    state.newsRecommend = await NewsAPI.newsRecommend(
      params: NewsRecommendRequestEntity(categoryCode: categoryCode),
      refresh: refresh,
      cacheDisk: true,
    );
    state.newsPageList = await NewsAPI.newsPageList(
      params: NewsPageListRequestEntity(categoryCode: categoryCode),
      refresh: refresh,
      cacheDisk: true,
    );
  }

  ///改变index
  void change() {
    state.recomIndex++;
    if (state.recomIndex > 2) state.recomIndex = 0;
  }

  /// 事件

  ///滑动到指定位置
  void scrollAnimToOffset(ScrollController controller, double offset,
      void Function() onScrollCompleted) {
    controller
        .animateTo(offset,
            duration: Duration(
              milliseconds: 200,
            ),
            curve: Curves.easeIn)
        .then((v) {
      if (onScrollCompleted != null) {
        onScrollCompleted();
      }
    }).catchError((e) {
      print(e);
    });
  }

  ///热播控制左右滑动一次
  PointerUpEventListener hotHPonit() {
    return (event) {
      //滑动间距
      hotHx = event.position.dx - state.hotH;
      //滑动间距大于20生效
      if (hotHx.abs() < 20) {
        return;
      }
      if (hotHx < -40) {
        nextponit = 350 * (last + 1);
        scrollAnimToOffset(hotControl, nextponit, () {
          last++;
          if (last > 2) last = 2;
        });
      } else if (hotHx > 40) {
        nextponit = 350 * (last - 1);
        scrollAnimToOffset(hotControl, nextponit, () {
          last--;
          if (last < 0) last = 0;
        });
      } else {
        scrollAnimToOffset(hotControl, 350.0 * last, () {});
      }
    };
  }

  /// 生命周期

  /// 初始
  @override
  void onInit() {
    super.onInit();
  }

  /// 可 async 拉取数据
  /// 可触发展示交互组件
  /// onInit 之后
  @override
  void onReady() {
    super.onReady();
    asyncLoadAllData();

    // ///定时刷新页面，实现推荐中的变化
    // Timer.periodic(Duration(seconds: 4), (t) {
    //   change();
    // });
    hotControl.addListener(() {});
  }

  /// 关闭页面
  /// 可以缓存数据，关闭各种控制器
  /// dispose 之前
  @override
  void onClose() {
    super.onClose();
  }

  /// 被释放
  /// 手动 释放各种内存资源
  @override
  void dispose() {
    super.dispose();
  }
}
